import cv2
import numpy as np

def detect_max_contour(img_path):
    # 1. 图像预处理
    img = cv2.imread(img_path)
    if img is None:
        raise FileNotFoundError("图像路径错误")  # 异常处理‌:ml-citation{ref="4,6" data="citationList"}
    
    # 灰度转换与降噪
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)  # 降维处理‌:ml-citation{ref="1,4" data="citationList"}
    blur = cv2.GaussianBlur(gray, (7,7), 0)  # 高斯核优化‌:ml-citation{ref="3,6" data="citationList"}
    
    # 动态阈值二值化
    _, binary = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)  # 自适应阈值‌:ml-citation{ref="3,4" data="citationList"}
    
    # 形态学闭合操作
    kernel = np.ones((3,3), np.uint8)
    closed = cv2.morphologyEx(binary, cv2.MORPH_CLOSE, kernel)  # 连接断裂边缘‌:ml-citation{ref="5,7" data="citationList"}
    
    # 2. 边缘检测与轮廓提取
    edges = cv2.Canny(closed, 50, 150)  # Canny双阈值‌:ml-citation{ref="1,3" data="citationList"}
    
    # 轮廓检测(适配OpenCV4.x版本)
    contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)  # 仅外轮廓‌:ml-citation{ref="6,7" data="citationList"}
    if len(contours) == 0:
        raise ValueError("未检测到有效轮廓")  # 空轮廓异常‌:ml-citation{ref="6" data="citationList"}
    
    # 3. 轮廓筛选与验证
    sorted_contours = sorted(contours, key=cv2.contourArea, reverse=True)
    contours = sorted_contours  # 面积最大轮廓‌:ml-citation{ref="6,7" data="citationList"}
    result = img.copy()
    max_contour = []
    for contour in contours:
        current_arr = []
        for c in contour:
            # current_arr.append(c[0])
            # max_contour = np.append(max_contour, c)
            print("contour=", c[0])
            x, y = c[0]
            cv2.circle(result, (x, y), 3, (0, 0, 255), -1)
        # max_contour.append(current_arr)
    # print(max_contour)
    # # 绘制结果
    
    
    # cv2.drawContours(result, max_contour, -1, (0,255,0), 2)  # 绿色轮廓线‌:ml-citation{ref="6" data="citationList"}
    
    # # 绘制边界框验证
    # x,y,w,h = cv2.boundingRect(max_contour)
    # cv2.rectangle(result, (x,y), (x+w,y+h), (255,0,0), 2)  # 蓝色边界框‌:ml-citation{ref="6,7" data="citationList"}
    
    # 结果保存
    cv2.imwrite('result.jpg', result)
    return result

# 执行检测
detect_max_contour('./data/images/6_1.png')
